package com.qinglian.controller;

import com.qinglian.utils.RedisUtil;
import com.qinglian.utils.Result;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.io.UnsupportedEncodingException;
import java.util.Random;

@RestController
public class SendEMail {
    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${spring.mail.username}")
    private String sendUserName;

    @GetMapping("/sendEMail")
    public Result<?> sendEMail(String account) {

        try {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setFrom(new InternetAddress(MimeUtility.encodeText("QingLian")+"<" + sendUserName + ">").toString()); //设置发送邮件账号
            simpleMailMessage.setTo(account); //设置接收邮件的人，可以多个
            simpleMailMessage.setSubject("QingLian邮箱验证码"); //设置发送邮件的主题
            Random random = new Random();
            int randomNumber = random.nextInt(900000) + 100000;
            simpleMailMessage.setText("「QingLian」您正在申请获取验证码,验证码为 " + randomNumber + " ,验证码有效期为5分钟。"); //设置发送邮件的内容
            mailSender.send(simpleMailMessage);
            redisUtil.set("code" + account,randomNumber,60*5);
            return  Result.success("邮件发送成功。");
        } catch (MailException | UnsupportedEncodingException e) {
            return Result.error("-1","邮件发送失败!");
        } catch (AddressException e) {
            throw new RuntimeException(e);
        }
    }

}
